package com.bwie.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.Product;
import com.bwie.service.ProductService;
import com.bwie.mapper.ProductMapper;

import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.ietf.jgss.MessageProp;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author 36167
* @description 针对表【product(商品表)】的数据库操作Service实现
* @createDate 2025-03-08 11:01:28
*/
@Service
 public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService{

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @DS("master")
    @Override
    public R prodlist(PageInfoVo pageInfoVo) {
        Integer pageNum=0;
        if (pageInfoVo.getPageNum()>0){
            pageNum=pageInfoVo.getPageNum()-1;
        }

        //构造分页参数
        PageRequest request=PageRequest.of(pageNum,pageInfoVo.getPageSize());


        BoolQueryBuilder builder = new BoolQueryBuilder();
        if (!StringUtils.isEmpty(pageInfoVo.getKeyWord()) && pageInfoVo.getKeyWord()!="" ){
           builder.must(QueryBuilders.matchQuery("name",pageInfoVo.getKeyWord()));
        }else if(pageInfoVo.getBeginTime()!=null && pageInfoVo.getEndTime()!=null){
            builder.must(QueryBuilders.rangeQuery("crateTime").format("yyyy-MM-dd HH:mm:ss").gt(pageInfoVo.getBeginTime()).lt(pageInfoVo.getEndTime()));
        }else {
            builder.must(QueryBuilders.matchAllQuery());
        }



        HighlightBuilder hig = new HighlightBuilder();
        hig.field("name").preTags("<font colour='red'>").postTags("</font>");

        NativeSearchQueryBuilder nati = new NativeSearchQueryBuilder();
        nati.withPageable(request).withHighlightBuilder(hig).withQuery(builder);

        SearchHits<Product> search = restTemplate.search(nati.build(), Product.class);

        long total = search.getTotalHits();

        ArrayList<Product> products = new ArrayList<>();

        for (SearchHit<Product> productSearchHit : search) {
            Product content = productSearchHit.getContent();
            List<String> name = productSearchHit.getHighlightField("name");
            if (name!=null && name.size()>0){
                content.setName(name.get(0));
            }
            products.add(content);
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("list",products);

        MessageProperties properties = new MessageProperties();
        properties.setHeader("x-delay",30000);
        Message build = MessageBuilder.withBody("fjlasjdlfas".getBytes()).andProperties(properties).build();
       rabbitTemplate.convertAndSend("day3-10","",build);
        return R.OK(map);
    }

    @Override
    public R sckill(String pid, String uid) {
        Long stock = stringRedisTemplate.opsForValue().decrement("stock:" + pid);
        if (stock<0){
             stringRedisTemplate.opsForValue().increment("stock:" + pid);
             return R.ERROR(500,"秒杀失败,库存不足");
         }

         String lock="lock:"+pid+":"+uid;

        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(lock, "1", 10, TimeUnit.SECONDS);
        if (!b){
            return R.ERROR(500,"秒杀失败,请勿重复提交");
        }
      sendOrderToQueue(pid,uid);
        return R.OK("秒杀成功");
    }

    private void  sendOrderToQueue(String pid,String uid){
        String xx=pid+","+uid;
        MessageProperties properties = new MessageProperties();
         properties.setHeader("x-delay",100);
        Message build = MessageBuilder.withBody(xx.getBytes()).andProperties(properties).build();
        rabbitTemplate.convertAndSend("day3-10","xty",build);
    }


}




